#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "stm32f10x.h"
#include "stm32f10x_i2c.h"

#include "public_lib.h"
#include "serial.h"
#include "24cxx.h"
#include "task.h"
#include "wdg_task.h"
#include "eeprom_task.h"

void start_eeprom_task(void *args)
{
    AT24CXX_Init();
}

int eeprom_task_run(void *args)
{
    
    
    return 0;
}

int eeprom_task_manage(int argc, char **argv, void *args)
{
    int err_code = -1;

    if(argc >= 2)
    {
        if(strcasecmp(argv[0], "eeprom")==0)
        {
            if(strcasecmp(argv[1], "read")==0)
            {
                if(argc == 4)
                {
                    unsigned short addr = atoi(argv[2]);
                    unsigned short len = atoi(argv[3]);
                    if(len > 256) {len = 256;}
                    unsigned char *p = malloc(len);
                    if(p)
                    {
                        manage_one_task(WDG_TASK, "iwdg feed");
                        manage_one_task(WDG_TASK, "wwdg feed");
                        AT24CXX_Read(addr, p, len);                        
                        serial_write("eeprom read :%02x", *p);
                        for(int i=1;i<len;i++)
                        {
                            serial_write("-%02x",*(p+i));
                        }
                        err_code = 0;
                        free(p);
                    }
                    else
                    {
                        serial_writeline("mem malloc failed");
                    }
                }
                else
                {
                    serial_writeline("%s %s usage:  %s %s addr len", argv[0], argv[1], argv[0], argv[1]);
                }
            }
            else if(strcasecmp(argv[1], "write")==0)
            {
                   if(argc == 4)
                {
                    unsigned short addr = atoi(argv[2]);
                    unsigned char data = atoi(argv[3]);
                    AT24CXX_Write(addr, &data, 1);
                    err_code = 0;
                }
                else
                {
                    serial_writeline("%s %s usage:  %s %s addr data", argv[0], argv[1], argv[0], argv[1]);
                }                
            }
        }     
        else{/* not for me, do nothing */}
    }
    else{/* not for me, do nothing */}

    return err_code;
}
